const express = require('express');
const router = express.Router();
const Joi = require("joi");
const pool = require('../utils/pool.js');
const Response = require('../utils/res');

//引入MySQL连接池
const jwt = require('jsonwebtoken')
const SECRET_KEY = 'JWT_SECRET_KEY'

/**
 * 处理后台登录业务
 */
router.post("/busiadmins", (req, resp,next)=>{
    let{muser, mpwd} = req.body
    // 表单验证
    let Admin = Joi.object({
      muser: Joi.string().required().pattern(new RegExp('^\\w{3,15}$')), // 必填
      mpwd: Joi.string().required().pattern(new RegExp('^\\w{6,15}$')), // 必填
    });
    let { error, value } = Admin.validate(req.body);
    if (error) {
      resp.send(Response.error(400, error));
      return; // 结束
    }
    let sql1 = 'select mid,ident,muser,mphone,avatars,access from merchant where muser=? and mpwd = MD5(?)'
    pool.querySync(sql1,[muser,mpwd]).then((result) => {
      if(result.length==0){
        resp.send(Response.error(1001, '账号密码输入错误'));
      }else{
        if(result[0].access){
          //查询数据库，账号密码是否填写正确
          let sql = "select mid,ident,muser,mphone,logo,access,shop,mname,avatars from merchant_info join merchant on meid=account join shop on me_name=mname where account=meid and muser=? and mpwd=MD5(?)"
          pool.query(sql, [muser, mpwd], (error, result)=>{
            if (error) {
              resp.send(Response.error(500, error));
              throw error;
            }
          
              // 获取登录用户对象
              let user = result[0]
              // 为该用户颁发一个token字符串，未来该客户端若做发送其他请求，则需要在请求Header中携带token，完成状态管理。
              let payload = {id: user.mid, muser: user.shop, ident:user.ident }
              let token = jwt.sign(payload, SECRET_KEY, {expiresIn: '1d'})
              // 返回user对象与token字符串
              resp.send(Response.ok({user, token}));
            })
          }else{
            // 获取登录用户对象
            let user = result[0]
            // 为该用户颁发一个token字符串，未来该客户端若做发送其他请求，则需要在请求Header中携带token，完成状态管理。
            let payload = {id: user.mid, muser: user.shop, ident:user.ident }
            let token = jwt.sign(payload, SECRET_KEY, {expiresIn: '1d'})
            // 返回user对象与token字符串
            resp.send(Response.ok({user, token}));
          }
      }
    }).catch((err) => {
      next(err)
    });
  });

  



  // 将router对象导出
  module.exports = router
